<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>标签</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
</head>

<body>
<div class="layui-container">
    <h1>标签ManyToManyField测试</h1>
    <a href="{% url 'create_article' %}" class="layui-btn">创建文章</a>
    <a href="{% url 'create_tag' %}" class="layui-btn">创建标签</a>
    <table class="layui-table">
        <thead>
        <tr>
            <th>标题</th>
            <th>标签</th>
            <th>编辑操作</th>
        </tr>
        </thead>
        <tbody>
        {% for article in articles %}
            <tr>
                <td>{{ article.title }}</td>
                <td>
                    {% for tag in article.tags.all %}
                        {{ tag.name }}{% if not forloop.last %}, {% endif %}
                    {% endfor %}
                </td>
                <td>
                    <a href="{% url 'edit_article' article.id %}" class="layui-btn layui-btn-xs">编辑</a>
                    <a href="{% url 'delete_article' article.id %}" class="layui-btn layui-btn-xs layui-btn-danger"
                       onclick="return confirm('确定要删除这篇文章吗？')">删除</a>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
<script src="https://www.layuicdn.com/layui-v2.5.6/layui.js "></script>
<script>
    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });
    document.getElementById('get-tags-btn').addEventListener('click', function () {
        fetch('{% url "get_tags" %}')
            .then(response => response.json())
            .then(data => {
                const tagListDiv = document.getElementById('tag-list');
                tagListDiv.innerHTML = '';
                data.tags.forEach(tag => {
                    const tagElement = document.createElement('p');
                    tagElement.textContent = `${tag.id}: ${tag.name}`;
                    tagListDiv.appendChild(tagElement);
                });
            })
            .catch(error => console.error('Error fetching tags:', error));
    });
</script>
</body>

</html>